/**
 * 
 */
package com.uit.trip_.location;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.uit.trip_.models.Trip;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.util.Log;
import android.widget.Toast;

/**
 * @author duongnguyen
 * 
 */
public class MyItemizedOverlay extends BalloonItemizedOverlay<OverlayItem> {

	private Context context;
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private Trip trip;

	public MyItemizedOverlay(Drawable defaultMarker, MapView mapView, Trip _trip) {
		super(boundCenter(defaultMarker), mapView);
		// TODO Auto-generated constructor stub
		context = mapView.getContext();
		this.trip = _trip;
	}

	public void addOverlay(OverlayItem item) {
		mOverlays.add(item);
		populate();
	}

	@Override
	protected OverlayItem createItem(int i) {
		// TODO Auto-generated method stub
		return mOverlays.get(i);
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return mOverlays.size();
	}

	@Override
	protected boolean onBalloonTap(int index, OverlayItem item) {
		// TODO Auto-generated method stub
		Toast.makeText(context, "Address:" + getMyAddress(), Toast.LENGTH_SHORT)
				.show();
		return super.onBalloonTap(index, item);
	}

	private String getMyAddress() {
		StringBuilder myAddress = new StringBuilder();
		Double la = Double.valueOf(trip.la);
		Double lng = Double.valueOf(trip.lng);
		Geocoder gc = new Geocoder(context, Locale.getDefault());
		List<Address> addresses = new ArrayList<Address>();
		try {
			addresses = gc.getFromLocation(la, lng, 5);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("duongnx", "error:" + e);
		}

		if (addresses.size() != 0) {
			Address address = addresses.get(0);
			for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
				if (i != address.getMaxAddressLineIndex() - 1) {
					myAddress.append(address.getAddressLine(i)).append(", ");
				} else {
					myAddress.append(address.getAddressLine(i));
				}
			}
		}
		if (myAddress == null || myAddress.equals("")) {
			return "Not found";
		}
		return myAddress.toString();
	}
}
